<template>
	<div class="address-list">
		<!-- 直接使用vant组件，具体参见官网 -->
		<van-address-list v-model="chosenAddressId" default-tag-text="默认" add-button-text="+添加地址" :list="addressList"
			@select="onSelect" @add="onAdd" @edit="onEdit" />
	</div>
</template>

<script>
	import { showToast } from 'vant';
	import { getAddressListAPI } from "@/api/address.js";
	export default {
		data() {
			return {
				chosenAddressId: 0,
				addressList: [],
			};
		},

		created() {
			//处理传过来的参数，比如创建订单页面时选择用户地址
			this.chosenAddressId = parseInt(this.$route.query.addressId) || 0;
			this.getAddressList();
		},

		methods: {
			//触发增加（此时addressEdit路由功能还没实现）
			onAdd() {
				this.$router.push({
					name: "addressEdit"
				});
			},

			//触发编辑（此时addressEdit路由功能还没实现）
			onEdit(item) {
				this.$router.push({
					name: "addressEdit",
					query: { id: item.id },
				});
			},

			//获取登录用户的收货地址
			getAddressList() {
				getAddressListAPI().then(result => {
					result.data.forEach((item) => {
						let { id, name, tel } = item;
						let address = item.city + item.county + item.address_detail;
						let isDefault = item.is_default == 1 ? true : false;
						this.addressList.push({
							id,
							name,
							tel,
							address,
							isDefault,
						});
						//默认选择
						if (item.is_default == 1) {
							this.active_id = item.id;
						}
					});
				}).catch(() => {});
			},

			//处理点击列表
			onSelect(item) {
				let addressId = item.id;
				//路由有addressId参数表明是要选择地址id的，把选择结果路由传参返回。
				if (this.$route.query.addressId) {
					this.$router.replace({
						name: "orderCreate",
						query: {
							addressId
						},
					});
				}
			},
		},
	};
</script>

<style scoped lang="less">
	@bgColor: #f8f8f8;
	@mainColor: #6366f1;  // 修改主色调为紫色

	.address-list {
		min-height: 100vh;
		background: @bgColor;

		/deep/ .van-address-list {
			padding: 12px;
			background: transparent;

			.van-address-item {
				margin-bottom: 12px;
				border-radius: 12px;
				box-shadow: 0 2px 8px rgba(0,0,0,0.1);
				
				&::after {
					display: none;
				}
			}

			.van-radio__icon--checked .van-icon {
				background: @mainColor;
				border-color: @mainColor;
			}

			.van-button--danger {
				background: linear-gradient(45deg, @mainColor, #8b5cf6);
				border: none;
				border-radius: 25px;
				margin: 16px;
			}

			.van-address-item__content {
				padding: 16px;
				
				.van-address-item__name {
					font-size: 16px;
					color: #1e293b;
				}
				
				.van-address-item__address {
					color: #64748b;
				}
			}
		}
	}
</style>